#ifndef XG_DB_CONNECTPOOL_CPP
#define XG_DB_CONNECTPOOL_CPP
////////////////////////////////////////////////////////
#include "../DBConnectPool.h"


DBConnectPool::DBConnectPool()
{
	creator = [&](){
		sp<DBConnect> conn(createConnect());

		if (conn && charset.length() > 0) conn->setCharset(charset);

		return conn;
	};
}
sp<DBConnect> DBConnectPool::get()
{
	sp<DBConnect> conn = ResPool<DBConnect>::get();

	if (conn && conn->getErrorCode())
	{
		disable(conn);

		return get();
	}

	return conn;
}
bool DBConnectPool::init(const string& filepath)
{
	ConfigFile file;

	CHECK_FALSE_RETURN(file.open(filepath));

	return init(file);
}
bool DBConnectPool::init(const ConfigFile& file)
{
	{
		SpinLocker lk(mtx);

		file.getVariable("HOST", cfg.ip);
		file.getVariable("USER", cfg.usr);
		file.getVariable("TYPE", cfg.type);
		file.getVariable("NAME", cfg.name);
		file.getVariable("PORT", cfg.port);
		file.getVariable("MAXSIZE", maxlen);
		file.getVariable("TIMEOUT", timeout);
		file.getVariable("CHARSET", charset);
		file.getVariable("PASSWORD", cfg.passwd);

		CHECK_FALSE_RETURN(maxlen > 0 && cfg.name.length() > 0);

		vec.clear();
	}

	sp<DBConnect> conn = get();

	CHECK_FALSE_RETURN(conn);

	if (strcmp(conn->getSystemName(), "SQLite") == 0) timeout = 0;

	return true;
}
DBConnectPool* DBConnectPool::Create(const ConfigFile& file)
{
	string dbdllpath;

	if (file.getVariable("DLLPATH", dbdllpath))
	{
		sp<DllFile> dll;
		CREATE_DBCONNECTPOOL_FUNC crtfunc = NULL;
		DESTROY_DBCONNECTPOOL_FUNC dsyfunc = NULL;

		if ((dll = DllFile::Get(dbdllpath)) && dll->read(crtfunc, "CreateDBConnectPool") && dll->read(dsyfunc, "DestroyDBConnectPool"))
		{
			DBConnectPool* dbconnpool = NULL;

			if ((dbconnpool = crtfunc()) == NULL) return dbconnpool;
			if (dbconnpool->init(file)) return dbconnpool;
			
			dsyfunc(dbconnpool);
		}
	}
	
	return NULL;
}
////////////////////////////////////////////////////////
#endif
